package com.by;


import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class Productor3 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接工厂   创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("erp");//虚拟主机 默认是 /
        factory.setPort(5672); //连接端口号
        factory.setHost("192.168.203.130");//服务器地址 默认是localhost
        factory.setUsername("admin");
        factory.setPassword("123456");

        //2.创建连接  资源自动释放（连接、信道 关闭）
        try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) {



            //3.5声明死信队列
            String q2="dl-queue";
            channel.queueDeclare(q2, true, false, false, null);

            //定义（死信）交换器
            String exName="deadEx"; //交换器的名称
            channel.exchangeDeclare(exName, BuiltinExchangeType.DIRECT);//路由键

            //绑定死信队列和死信交换器  路由键 与正常队列的路由键保持一致
            channel.queueBind(q2,exName,"deadKey");



            //3.声明正常队列
            String queueName = "order";
            Map<String,Object> arg=new HashMap<>();
            arg.put("x-dead-letter-exchange",exName);//指明当前队列中产生的死信  投递到哪个交换器
            //如果死信交换器与正常交换器绑定队列时  路由键不一致时，必须指定死信路由键的名称
            arg.put("x-dead-letter-routing-key","deadKey");
            channel.queueDeclare(queueName, true, false, false, arg);

            //3.1 声明正常交换器
            String noramlEx="orderEx";
            channel.exchangeDeclare(noramlEx,BuiltinExchangeType.DIRECT);

            //3.2绑定正常队列与交换器
            channel.queueBind(queueName,noramlEx,"order");



            //4.发布消息
            /**
             * 消息持久化  MessageProperties.PERSISTENT_TEXT_PLAIN
             *
             */
            AMQP.BasicProperties properties = new AMQP.BasicProperties()
                    .builder()
                    .expiration("10000") //设置消息过期时间 单位是ms
                    .build();
            channel.basicPublish(noramlEx, "order", properties, "dd20240001".getBytes());


            System.out.println("消息发布完毕，服务器已收到");

        }


    }
}